package com.sixmac.controller;

import com.google.common.base.Strings;
import com.sixmac.annotation.AuthUser;
import com.sixmac.common.base.BaseController;
import com.sixmac.core.annotation.Validator;
import com.sixmac.core.base.model.Format;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.module.*;
import com.sixmac.platform.service.RoomService;
import com.sixmac.util.Push;
import com.sixmac.util.WeChatConfig;
import com.sixmac.utils.LockManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by admin on 2018/9/3.
 */
@Controller
@ResponseBody
@RequestMapping("/room")
public class RoomController extends BaseController {
    @Autowired
    RoomService roomService;
    @Autowired
    WeChatConfig weChatConfig;
    /**
     * @api {post} /room/index 0.1 房屋管理
     * @apiName room.index
     * @apiGroup room
     * @apiParam {String} token token
     * @apiParam {String} page page
     * @apiParam {String} size size
     * @apiSuccess {String} user.code 111表示用户第一次登陆，需要创建用户 调用接口03
     * @apiSuccess {String} user.id 房屋id
     * @apiSuccess {String} user.name 房东名称
     * @apiSuccess {String} user.address 地址
     * @apiSuccess {String} user.s 1空闲2入住
     * @apiSuccess {String} user.images 房屋图片，多个用,分隔
     * @apiSuccess {String} user.lockNo 编号
     * @apiSuccess {String} status 0空闲1入住中
     */
    @AuthUser
    @RequestMapping("/index")
    public AjaxResult index(Tenant tenant, @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "5") Integer size) {
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+tenant.getId(),null);
        Room room = Blade.create(TenantRoom.class).findById(tenantRoom.getRoomId());
        Landlord landlord = Blade.create(Landlord.class).findById(room.getLandlordId());
        return roomService.index(landlord, page, size);
    }


    /**
     * @api {post} /room/addTenant 0.2.1添加租户
     * @apiName room.addTenant
     * @apiGroup room
     * @apiParam {String} token token
     * @apiParam {String} roomId 房屋id
     * @apiParam {String} phone 手机号码
     * @apiParam {String} name 房东名称
     * @apiParam {String} sex 性别 1男2女
     * @apiParam {String} contract 合同照片
     * @apiParam {String} idCard 身份证号码
     * @apiParam {String} idCardFront 身份证正面
     * @apiParam {String} idCardReverse 身份证反面
     * @apiParam {String} contract 租房合同
     * @apiParam {String} start 开始时间（2018-09-03）
     * @apiParam {String} end 结束时间（2018-09-03）
     */
    @AuthUser
    @Validator(name = {"roomId", "name", "phone", "sex",
            "idCard", "idCardFront", "idCardReverse", "contract",
            "start", "end"}, format = {Format.NOT_NULL, Format.NOT_NULL,
            Format.REG_PHONE, Format.NOT_NULL, Format.NOT_NULL, Format.NOT_NULL,
            Format.NOT_NULL, Format.NOT_NULL, Format.NOT_NULL, Format.NOT_NULL
    })
    @RequestMapping("/addTenant")
    public AjaxResult addTenant(Tenant tenant, Integer roomId, String name, String phone, Integer sex,
                                String idCard, String idCardFront,
                                String idCardReverse, String contract,
                                String start, String end) {

        Contract contract1 = new Contract();
        contract1.setContract(contract);
        contract1.setEndTime(DateKit.parseDate(end));
        contract1.setStartTime(DateKit.parseDate(start));
        contract1.setIdCard(idCard);
        contract1.setName(name);
        contract1.setSex(sex);
        contract1.setMobile(phone);
        contract1.setIdCardFront(idCardFront);
        contract1.setIdCardReverse(idCardReverse);

        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+tenant.getId(),null);
        Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());
        Landlord landlord = Blade.create(Landlord.class).findById(room.getLandlordId());

        return roomService.addTenant(contract1, landlord, roomId, start, end);
    }

    /**
     * @api {post} /room/getTenantByPhone 0.2.2 通过手机号码，获取租户信息
     * @apiName room.getTenantByPhone
     * @apiGroup room
     * @apiParam {String} token token
     * @apiParam {String} phone 手机号码
     * @apiSuccess {String} roomId 房屋id
     * @apiSuccess {String} phone 手机号码
     * @apiSuccess {String} name 房东名称
     * @apiSuccess {String} sex 性别 1男2女
     * @apiSuccess {String} birthday 出生日期 比如（2018-09-03）
     * @apiSuccess {String} region 区域
     * @apiSuccess {String} contract 合同照片
     * @apiSuccess {String} idCard 身份证号码
     * @apiSuccess {String} businessLicense 经营许可证
     * @apiSuccess {String} idCardFront 身份证正面
     * @apiSuccess {String} idCardReverse 身份证反面
     * @apiSuccess {String} contract 租房合同
     * @apiSuccess {String} startDate 开始时间
     * @apiSuccess {String} endDate 结束时间
     */
    @AuthUser
    @Validator(name = {"phone"}, format = {Format.NOT_NULL})
    @RequestMapping("/getTenantByPhone")
    public AjaxResult getTenantByPhone(String phone) {
        return roomService.getTenantByPhone(phone);
    }

    /**
     * @api {post} /room/getRoom 0.3.1 房屋详情
     * @apiName room.getRoom
     * @apiGroup room
     * @apiParam {String} token token
     * @apiParam {String} roomId 房屋id
     * @apiSuccess {String} tenantRoomId tenantRoomId
     * @apiSuccess {String} approve 入住申请 3申请中 1,2 不管
     * @apiSuccess {String} name 房客名称
     * @apiSuccess {String} sex 性别 1男2女
     * @apiSuccess {String} mobile 手机号码
     * @apiSuccess {String} images 用户身份证正面，反面，合同
     * @apiSuccess {String} time 租住日期
     * @apiSuccess {String} list 入住用户
     * @apiSuccess {String} history 历史记录
     */
    @AuthUser
    @RequestMapping("/getRoom")
    public AjaxResult getRoom(Tenant tenant, Integer roomId) {
        Room room = Blade.create(Room.class).findById(roomId);
        Landlord landlord = Blade.create(Landlord.class).findById(room.getLandlordId());
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" tenantId="+tenant.getId()+" and landlordId="+landlord.getId()+" and roomId="+roomId+" and status = 1",null);
        if (tenantRoom.getIsAdmin()!=2&&tenantRoom.getAdminTime()==null){
            return error("不是管理员");
        }
        return roomService.getRoomByAdmin(landlord, roomId,tenantRoom.getAdminTime());
    }

    /**
     * @api {post} /room/passRoom 0.3.2 通过or拒绝
     * @apiName room.passRoom
     * @apiGroup room
     * @apiParam {String} token token
     * @apiParam {String} tenantRoomId tenantRoomId
     * @apiParam {String} type 1通过2拒绝
     * @apiParam {String} start 通过状态需要开始时间2018-09-04
     * @apiParam {String} end 通过状态需要结束时间2018-09-04
     * @apiSuccess {String} history 历史记录
     */
    @AuthUser
    @RequestMapping("/passRoom")
    public AjaxResult passRoom(Tenant tenant, Integer tenantRoomId, Integer type, String start, String end,String info) {
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findById(tenantRoomId);
        Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());
        if (tenantRoom.getApprove() != 3)
            return error("状态错误。");

        Tenant t = Blade.create(Tenant.class).findById(tenantRoom.getTenantId());
        if (type == 1) {
            if (Strings.isNullOrEmpty(start) || Strings.isNullOrEmpty(end))
                return error("入住周期未设置。");
            //房客状态设置为入住
            tenantRoom.setApprove(1);
            tenantRoom.setStatus(1);//通过，入住中
            tenantRoom.setStartDate(DateKit.parseTime(start+" 00:00:00"));
            tenantRoom.setEndDate(DateKit.parseTime(end+" 23:59:59"));

            Contract contract1 = new Contract();
            contract1.setContract(tenantRoom.getContract());
            contract1.setEndTime(DateKit.parseTime(end+" 23:59:59"));
            contract1.setStartTime(DateKit.parseTime(start+" 00:00:00"));
            contract1.setIdCard(t.getIdCard());
            contract1.setName(t.getName());
            contract1.setSex(t.getSex());
            contract1.setMobile(t.getMobile());
            contract1.setIdCardFront(t.getIdCardFront());
            contract1.setIdCardReverse(t.getIdCardReverse());
            contract1.setHandCard(t.getHandCard());
            contract1.setStatus(0);//入住
            contract1.setTentantId(tenantRoom.getTenantId());
            contract1.setRoomId(room.getId());
            contract1.setTenantRoomId(tenantRoomId);
            Blade.create(Contract.class).save(contract1);

            //推送模板消息
            Push push = new Push();
            push.sendSucess(contract1,weChatConfig);

        } else {
            tenantRoom.setApprove(2);
            tenantRoom.setStatus(2);//申请拒绝，退租
            tenantRoom.setInfo(info);

            Push push = new Push();
            push.sendError(t,info,weChatConfig);
        }

        Blade.create(TenantRoom.class).update(tenantRoom);
        return success("操作成功");
    }

    /**
     * @api {post} /room/cancelRoom 0.3.3 退租
     * @apiName room.cancelRoom
     * @apiGroup room
     * @apiParam {String} token token
     * @apiParam {String} tenantRoomId tenantRoomId
     */
    @AuthUser
    @RequestMapping("/cancelRoom")
    public AjaxResult cancelRoom(Tenant tenant,Integer type, Integer id,String formId) {
        if (type ==0){//退单个
            TenantRoom tenantRoom = Blade.create(TenantRoom.class).findById(id);
            Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());
            tenantRoom.setStatus(2);
            tenantRoom.setApprove(2);
            Contract contract = Blade.create(Contract.class).findFirstBy(" tenantRoomId = "+tenantRoom.getId(),null);
            contract.setStatus(1);
//            Push push = new Push();
//            push.sendOut(contract,weChatConfig);
            if (tenantRoom.getFingerprint()!=null) {
//                LockManage lockManage = new LockManage();
//                LockUser lockUser = new LockUser();
//                lockUser.setMsgId("" + tenantRoom.getId());
//                lockUser.setDeviceCode(room.getLockNo());
//                lockUser.setLockUserInfo(tenantRoom.getFingerprint());
//                lockManage.deleteUser(lockUser);
            }
            Blade.create(Contract.class).update(contract);
            Blade.create(TenantRoom.class).update(tenantRoom);
        }else{
            //退全部
            List<TenantRoom> tenantRoom = Blade.create(TenantRoom.class).findBy(" roomId="+id+" and status = 1 and tenantId!="+tenant.getId(),null);
            for (TenantRoom tenantRoom1:tenantRoom){
                tenantRoom1.setStatus(2);
                tenantRoom1.setApprove(2);
                Contract contract = Blade.create(Contract.class).findFirstBy(" tenantRoomId = "+tenantRoom1.getId(),null);
                contract.setStatus(1);
//                Push push = new Push();
//                push.sendOut(contract,weChatConfig);

                if (tenantRoom1.getFingerprint()!=null){
                }
                Blade.create(Contract.class).update(contract);
                Blade.create(TenantRoom.class).update(tenantRoom1);
            }
        }
        return success("退租成功");
    }

    @AuthUser
    @RequestMapping("/defence")
    public AjaxResult defence(Tenant tenant, Integer roomId) {
        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" tenantId = "+tenant.getId()+" and roomId="+roomId+" and status =1 ",null);
        if (tenantRoom == null){
            return error("操作失败");
        }
        tenantRoom.setDefenceTime(new Date());
        tenantRoom.setDefence((tenantRoom.getDefence()==null||tenantRoom.getDefence()==0)?1:0);
        Blade.create(TenantRoom.class).update(tenantRoom);
        return success("成功");
    }
}
